package com.voxel.sense.infomsg.module.task.execution.file;

import android.app.ProgressDialog;
import android.content.Context;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.download.DownloadListener;

import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.interfaces.listener.UploadListenerImp;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.OpenDocuIntentUtils;
import com.voxel.sense.infomsg.utils.UploadManager;
import com.voxel.sense.infomsg.utils.UploadUtils;
import com.voxel.sense.infomsg.widget.ProgressDialogs;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.TaskFileListEntity;
import cyy.example.com.facotry.net.helper.TaskNetHelper;
import io.github.lizhangqu.coreprogress.ProgressUIListener;

/**
 * @author ChenYiYao
 * @date 2018/5/14
 * des :
 */
public class TaskFileOperationPresenter extends BasePresenter<TaskFileOperationContract.View>
        implements TaskFileOperationContract.Presenter, DataSource.Callback<BaseEntity<TaskFileListEntity>> {

    private List<String> mDeleteDatas;
    private UploadManager mUploadManager;
    private boolean mIsLoading = false;
    private String filename;

    private Context context;
    public TaskFileOperationPresenter(TaskFileOperationContract.View view, Context context) {
        super(view);
        this.context = context;
    }

    @Override
    public void start() {
        super.start();
        mDeleteDatas = new ArrayList<>();

    }

    @Override
    public void getFileList(String TaskNumb) {
        mView.showLoading("", false);
        TaskNetHelper.getTaskFileList(TaskNumb, this);
    }

    @Override
    public void doUploadFile(String taskNum, List<MultiItemBean<String>> addFiles, String formContents, List removeFiles) {
        if (!NetworkUtils.isConnected()) {
            mView.showError(Factory.app().getResources().getString(R.string.network_unavailable));
            return;
        }

        //将需要上传的文件装入集合
        List<String> list = new ArrayList<>();
        for (MultiItemBean<String> itemBean : addFiles) {
            if (itemBean.getType() == TaskFileOperationContract.LOCAL_IMAGE_TYPE
                    || itemBean.getType() == TaskFileOperationContract.LOCAL_DOC_TYPE) {
                list.add(itemBean.getData());
            }
        }

        if (mUploadManager == null) {
            mUploadManager = new UploadManager();
            mUploadManager.setShowProgress(true);
            mUploadManager.initProgressDialog((Context) mView, "上传图片");
        }

        Map<String, String> stringMap = new HashMap<>();
        stringMap.put("taskNumber", taskNum);
        long l = System.currentTimeMillis();
        //若无上传图片，无需显示上传dialog
        boolean empty = ListUtil.isEmpty(list);
        if (empty) {
            mUploadManager.setShowProgress(false);
            mView.showLoading("");
        } else {
            mUploadManager.setShowProgress(true);
        }
        mUploadManager.getPostUpTaskFileRequest(l + "", taskNum, mDeleteDatas, list, formContents, new UploadListenerImp<String>() {
            /**
             * 上传过程中的问题，中断，取消等。
             * @param progress
             */
            @Override
            public void onStart(Progress progress) {
                super.onStart(progress);
            }

            @Override
            public void onFinish(String str, Progress progress) {
                super.onFinish(str, progress);
                if (mView != null) {
                    mView.dimissLoading();
                    try {
                        BaseEntity baseEntity = Factory.getGson().fromJson(str, BaseEntity.class);
                        if (baseEntity.isSuccess()) {
                            //上传成功，刷新数据

                            ToastUtil.showToastShort(context, "保存成功");

                            if (!empty) {
                                //上传成功，但这时还需要刷新数据，重新调用接口获取已上传图片的地址
                                getFileList(taskNum);
                            }
                            mDeleteDatas.clear();
                        } else {
                            mView.showSnackBarWarning("上传失败");
                        }
                    } catch (Exception e) {
                        mView.showSnackBarWarning("上传失败");
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Progress progress) {
                super.onError(progress);
                mView.showSnackBarWarning("上传失败");
            }
        });
    }

    @Override
    public void doAddImage(List<MultiItemBean<String>> adapterDatas, List<String> list) {
        if (!ListUtil.isEmpty(adapterDatas)) {
            List<MultiItemBean<String>> newBeans = new ArrayList<>();
            MultiItemBean flagBean = null;
            if (!ListUtil.isEmpty(list)) {
                for (String url : list) {
                    String fileName = FileUtils.getFileName(url);
                    newBeans.add(new MultiItemBean(url, TaskFileOperationContract.LOCAL_IMAGE_TYPE,fileName));
                }
            }
            int netImageCount = 0;
            boolean haveImageDes = false;
            //先移除原有的数据
            for (int i = adapterDatas.size() - 1; i >= 0; i--) {
                //倒叙获取到原有的本地图片
                MultiItemBean<String> itemBean = adapterDatas.get(i);
                if (itemBean.getType() == TaskFileOperationContract.NET_IMAGE_TYPE) {
                    netImageCount++;
                } else if (itemBean.getType() == TaskFileOperationContract.LOCAL_IMAGE_TYPE) {
                    //将旧的本地图片加入删除集合中
                    adapterDatas.remove(itemBean);
                } else if (itemBean.getType() == TaskFileOperationContract.DOC_DESC_TYPE) {
                    //若是文档的title，则记录下该下标，作为新数据的插入位置。
                    flagBean = itemBean;
                } else if (itemBean.getType() == TaskFileOperationContract.IMAGE_DESC_TYPE) {
                    //倒叙开始遍历，由于文档固定排在图片后面。走到IMAGE_DESC_TYPEE类型，则代表已遍历完所有图片
                    if (netImageCount == 0 && ListUtil.isEmpty(newBeans)) {
                        adapterDatas.remove(i);
                    }
                    haveImageDes = true;
                    break;
                }
            }

            //新的数据源
            List<MultiItemBean<String>> beans = new ArrayList<>();
            beans.addAll(adapterDatas);
            if (!haveImageDes) {
                //未有图片存在，则在第0个位置添加
                MultiItemBean<String> itemBean = beans.get(0);
                int titleIndex = itemBean.getType() == TaskFileOperationContract.ADD_TYPE ? 1 : 0;
                beans.add(titleIndex, new MultiItemBean<>("图片附件", TaskFileOperationContract.IMAGE_DESC_TYPE));
                beans.addAll(titleIndex + 1, newBeans);
            } else if ( flagBean != null) {
                int i = beans.indexOf(flagBean);
                beans.addAll(i, newBeans);
            } else  {
                //没有文档类型文件，直接在尾部添加
                beans.addAll(newBeans);
            }
            netImageCount = netImageCount + newBeans.size();
            mView.onRecordImageCount(netImageCount, "");
            mView.onRefreshFilesList(beans);
        } else if (!ListUtil.isEmpty(list)) {
            //无任何文件的情况
            List<MultiItemBean<String>> beans = new ArrayList<>();
            beans.add(0, new MultiItemBean<>("图片附件", TaskFileOperationContract.IMAGE_DESC_TYPE));
            for (String url : list) {
                beans.add(new MultiItemBean(url, TaskFileOperationContract.LOCAL_IMAGE_TYPE));
            }
            mView.onRecordImageCount(beans.size(), "");
            mView.onRefreshFilesList(beans);
        }
    }

    @Override
    public void doAddSelelctDocs(List<MultiItemBean<String>> adapterDatas, List<String> list) {
        if (!ListUtil.isEmpty(adapterDatas)) {
            List<MultiItemBean<String>> newBeans = new ArrayList<>();
            if (!ListUtil.isEmpty(list)) {
                for (String url : list) {
                    String fileName = FileUtils.getFileName(url);
                    newBeans.add(new MultiItemBean(url, TaskFileOperationContract.LOCAL_DOC_TYPE,fileName));
                }
            }
            //数据插入的位置
            int netDocCount = 0;
            boolean haveDoc = false;
            for (int i = adapterDatas.size() - 1; i >= 0; i--) {
                MultiItemBean<String> itemBean = adapterDatas.get(i);
                if (adapterDatas.get(i).getType() == TaskFileOperationContract.DOC_DESC_TYPE) {
                    //是title类型，则表示文件类型的文件遍历完成
                    haveDoc = true;
                    if (netDocCount == 0 && newBeans.size() < 1) {
                        adapterDatas.remove(i);
                    }
                    break;
                } else if (itemBean.getType() == TaskFileOperationContract.LOCAL_DOC_TYPE) {
                    adapterDatas.remove(i);
                } else if (itemBean.getType() == TaskFileOperationContract.NET_DOC_TYPE) {
                    netDocCount++;
                }
            }

            //新的数据源
            List<MultiItemBean<String>> beans = new ArrayList<>();
            beans.addAll(adapterDatas);
            if (!haveDoc) {
                beans.add(new MultiItemBean<>("其它附件", TaskFileOperationContract.DOC_DESC_TYPE));
            }
            beans.addAll(newBeans);
            //已在网络端的图片和新增的和，则是总数量
            mView.onRecordDocCount(netDocCount + newBeans.size());
            mView.onRefreshFilesList(beans);
        } else if (!ListUtil.isEmpty(list)) {
            //无任何文件的情况
            List<MultiItemBean<String>> beans = new ArrayList<>();
            beans.add(0, new MultiItemBean<>("其它附件", TaskFileOperationContract.DOC_DESC_TYPE));
            for (String url : list) {
                beans.add(new MultiItemBean(url, TaskFileOperationContract.LOCAL_DOC_TYPE));
            }
            mView.onRecordDocCount(beans.size());
            mView.onRefreshFilesList(beans);
        }
    }

    @Override
    public void removeFile(List<MultiItemBean<String>> adapterDatas, MultiItemBean<String> removeBean) {

        if (removeBean.getType() == TaskFileOperationContract.LOCAL_DOC_TYPE) {
            removeDoc(adapterDatas);
        } else if (removeBean.getType() == TaskFileOperationContract.NET_DOC_TYPE) {
            removeDoc(adapterDatas);
            mDeleteDatas.add(removeBean.getData());
        } else if (removeBean.getType() == TaskFileOperationContract.NET_IMAGE_TYPE) {
            removeImage(adapterDatas);
            mDeleteDatas.add(removeBean.getData());
        } else if (removeBean.getType() == TaskFileOperationContract.LOCAL_IMAGE_TYPE) {
            removeImage(adapterDatas);
        }
    }

    @Override
    public void LookDocs(MultiItemBean<String> bean) {
        int type = bean.getType();
        File cacheDir = AppFileUtil.getCacheDir();
        String data = bean.getData();
        File file = new File(cacheDir, data);
        boolean fileExists = FileUtils.isFileExists(file);
        if (type == TaskFileOperationContract.LOCAL_DOC_TYPE) {
            //本地文件直接打开
            OpenDocuIntentUtils.OpenFile(new File(data), Factory.app());
        } else if (fileExists) {
            //网络文件，但已存在
            OpenDocuIntentUtils.OpenFile(file, Factory.app());
        } else {
            DownFile(CommonConstants.FILE_TASK_URL , data, cacheDir);
        }
    }

    private void removeDoc(List<MultiItemBean<String>> adapterDatas) {
        //删除文档
        boolean flag = true;
        for (int i = adapterDatas.size() - 1; i >= 0; i--) {
            int type = adapterDatas.get(i).getType();
            if (flag && (type == TaskFileOperationContract.LOCAL_DOC_TYPE
                    || type == TaskFileOperationContract.NET_DOC_TYPE)) {
                flag = false;
            } else if (type == TaskFileOperationContract.DOC_DESC_TYPE && flag) {
                adapterDatas.remove(adapterDatas.get(i));
                mView.notifychange();
                break;
            } else {
                break;
            }
        }
    }

    private void removeImage(List<MultiItemBean<String>> adapterDatas) {
        //删除文档
        boolean flag = true;
        int removeIndex = -1;
        for (int i = 0; i < adapterDatas.size(); i++) {
            int type = adapterDatas.get(i).getType();
            if (type == TaskFileOperationContract.IMAGE_DESC_TYPE) {
                removeIndex = i;
            } else if (type == TaskFileOperationContract.NET_IMAGE_TYPE
                    || type == TaskFileOperationContract.LOCAL_IMAGE_TYPE) {
                flag = false;
                break;
            } else if (i != 0) {
                break;
            }
        }
        if (flag && removeIndex != -1) {
            adapterDatas.remove(removeIndex);
            mView.notifychange();
        }

    }


    @Override
    public void onDataLoaded(BaseEntity<TaskFileListEntity> data, int reqId) {
        mView.dimissLoading();
        if (data.isSuccess()) {
            TaskFileListEntity files = data.getData();
            if (files != null && !ListUtil.isEmpty(files.getFiles())) {
                List<MultiItemBean<String>> docList = new ArrayList<>();
                List<MultiItemBean<String>> imageList = new ArrayList<>();
                int imageCount = 0;
                int docCount = 0;
                for (TaskFileListEntity.ImgTxtFile file : files.getFiles()) {
                    String fileExtension = FileUtils.getFileExtension(file.getTaskFileName());
                    if (vertifyImage(fileExtension)) {
                        imageList.add(new MultiItemBean<>(file.getTaskFilePath(), TaskFileOperationContract.NET_IMAGE_TYPE,file.getTaskFileName()));
                        imageCount++;
                    } else if (!vertifyVedio(fileExtension)) {
                        docCount++;
                        docList.add(new MultiItemBean<>(file.getTaskFilePath(), TaskFileOperationContract.NET_DOC_TYPE,file.getTaskFileName()));
                    }
                }

                List<MultiItemBean<String>> newDatas = new ArrayList<>();
                if (!ListUtil.isEmpty(imageList)) {
                    newDatas.add(new MultiItemBean<>("图片附件", TaskFileOperationContract.IMAGE_DESC_TYPE));
                    newDatas.addAll(imageList);
                }
                if (!ListUtil.isEmpty(docList)) {
                    newDatas.add(new MultiItemBean<>("其它附件", TaskFileOperationContract.DOC_DESC_TYPE));
                    newDatas.addAll(docList);
                }
                mView.onRefreshFilesList(newDatas);
                mView.onRecordImageCount(imageCount, files.getFormContents());
                mView.onRecordDocCount(docCount);
            }
        }
    }

    private boolean vertifyImage(String fileExtension) {
        String s = fileExtension.toUpperCase();
        boolean b = false;
        if ("JPEG".equals(s) || "GIF".equals(s) || "PNG".equals(s) || "JPG".equals(s)) {
            b = true;
        }
        return b;
    }

    private boolean vertifyVedio(String fileExtension) {
        String s = fileExtension.toUpperCase();
        boolean b = false;
        if ("MP4".equals(s) || "M4A".equals(s) || "WMV".equals(s) ) {
            b = true;
        }
        return b;
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView != null) {
            mView.dimissLoading();
        }

    }


    private void DownFile(final String url, final String fileName, final File cacheDir) {
        if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
            return;
        }

        if (mIsLoading)
            return;
//        ProgressDialogs dialog = new ProgressDialogs(context);
        filename = UploadUtils.getInstent().downloadFile(url + fileName, new ProgressUIListener() {
            @Override
            public void onUIProgressStart(long totalBytes) {
                if (mView == null)
                    return;
                mIsLoading = true;
                mView.showLoading("", false);
//                dialog.setProgressMax((int) totalBytes);
//                dialog.show();
            }

            @Override
            public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
//                dialog.setProgress((int)numBytes, (int)totalBytes);
            }

            @Override
            public void onUIProgressFinish() {
                if (mView == null)
                    return;
                mIsLoading = false;
                mView.dimissLoading();
//                dialog.dismiss();
                OpenDocuIntentUtils.OpenFile(new File(filename), Factory.app());
            }
        });
//        UploadUtils.getInstent().getPostDownRequest(cacheDir.getAbsolutePath(), fileName, fileName, new DownloadListener(fileName) {
//            @Override
//            public void onStart(Progress progress) {
//                if (mView == null)
//                    return;
//                mIsLoading = true;
//                mView.showLoading("", false);
//            }
//
//            @Override
//            public void onProgress(Progress progress) {
//
//            }
//
//            @Override
//            public void onError(Progress progress) {
//                if (mView == null)
//                    return;
//                mIsLoading = false;
//                mView.dimissLoading();
//                ToastUtil.showToastLong(Factory.app(), "下载失败");
//                FileUtils.deleteAllFile(new File(cacheDir, fileName));
//            }
//
//            @Override
//            public void onFinish(File file, Progress progress) {
//                if (mView == null)
//                    return;
//                mIsLoading = false;
//                mView.dimissLoading();
//                OpenDocuIntentUtils.OpenFile(file, Factory.app());
//            }
//
//            @Override
//            public void onRemove(Progress progress) {
//                if (mView == null)
//                    return;
//                mIsLoading = false;
//                mView.dimissLoading();
//            }
//        });
    }

}


